package adminorg;

import com.oros.db.AETableContainer;

import de.rac.vaadin.framework.ui.*;

import com.oros.db.*;
import com.vaadin.data.Container.Filter;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.filter.Compare;
import com.vaadin.ui.*;
import com.vaadin.ui.Window.Notification;

import java.util.*;
public abstract class DefaultWindow extends GeneralWindow implements TableSource {

	private static final long serialVersionUID = -5335848601148570620L;
    protected AETableContainer container;
	protected AELikeFilter likeFilter;
	protected DatabaseHelper dbHelp;
	protected LinkedHashMap<String,EditFormField> editColumnHeaderMap=new LinkedHashMap<String,EditFormField>();
    protected boolean isReadAllowed=true,isWriteAllowed=true,isCreateAllowed=true;
    protected boolean ReadAllowedStatus=false;
    protected String CompAcc_AuthColumn;
	public DefaultWindow(DatabaseHelper dbHelp)
    {
    	this.dbHelp = dbHelp;
    	this.setSourceData(this);
    }
	@Override
	public boolean getReadAllowed() {
		if (!ReadAllowedStatus)
		{
			if (CompAcc_AuthColumn!=null && CompAcc_AuthColumn.length()>0)
			{
				isReadAllowed=false;
				try
				{
					AETableContainer aContainer = dbHelp.getCurrentUserParamContainer();
					//System.out.println("Verified rights for "+sourceData.getViewTable()+" with "+aContainer.size());
					HashSet<?> dat=aContainer.getDistinctColumnValues(CompAcc_AuthColumn);
					for(Object d:dat)
					{
                       if (d instanceof Boolean) if  (((Boolean)d).booleanValue())
                       {
                    	   isReadAllowed=true;
                    	   break;
                       }
					}
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
			else isReadAllowed=true;
			ReadAllowedStatus=true;
		}
		return isReadAllowed;
	}

	@Override
	public boolean getWriteAllowed() {
		return isWriteAllowed;
	}

	@Override
	public boolean getCreateAllowed() {
		return isCreateAllowed;
	}
    @Override
	public AETableContainer viewTableInit() throws Exception {
    	return container;
    }
	@Override
	public AETableContainer getViewTable() {
		return container;
	}

	@Override
	public EditFormField getEditColumnHeader(Object columnName) {
		return editColumnHeaderMap.get(columnName);
	}

	@Override
	public void updateColumnLikeFilter(int columnNo, String value) {
    	if (likeFilter!=null) likeFilter.updateFilter(columnNo, value);
	}
	
    protected void likeFilterInit(int[] likeFilterKind)
    {
  	  likeFilter= new AELikeFilter(getViewColumns(),likeFilterKind,null);
  	  container.addContainerFilter(likeFilter);
    }
    protected void setLikeFilterAsAllMiddleCaseInsensitive()
    {
    	int n=getViewColumns().length;
    	int[] likeFilterKind=new int[n];
    	for(int i=0;i<n;i++) likeFilterKind[i]=AELikeFilter.KIND_MIDDLE;
    	likeFilterInit(likeFilterKind);
    }
    protected ResourcePool getActiveSpecificResourceTranslated(String sAddingNewRecord,
    		String sEditingRecord,String sNoRecordIsChosen,String sRecordDeleting,String sRecordWillBeRemoved,
    		String sFieldMustBeUnique)
    {
    	ResourcePool resource = dbHelp.getResource();
    	String table_AddingNewRecord=dbHelp.getWords(sAddingNewRecord);
    	resource.setSpecificLanguageData("table_AddingNewRecord", table_AddingNewRecord);
    	String table_EditingRecord=dbHelp.getWords(sEditingRecord);
    	resource.setSpecificLanguageData("table_EditingRecord", table_EditingRecord);
    	String table_NoRecordIsChosen=dbHelp.getWords(sNoRecordIsChosen);
    	resource.setSpecificLanguageData("table_NoRecordIsChosen", table_NoRecordIsChosen);
    	String table_RecordDeleting=dbHelp.getWords(sRecordDeleting);
    	resource.setSpecificLanguageData("table_RecordDeleting", table_RecordDeleting);
    	String table_RecordWillBeRemoved=dbHelp.getWords(sRecordWillBeRemoved);
    	resource.setSpecificLanguageData("table_RecordWillBeRemoved", table_RecordWillBeRemoved);
    	if (sFieldMustBeUnique!=null)
    	{
    	   String table_FieldMustBeUnique=dbHelp.getWords(sFieldMustBeUnique);
    	   resource.setSpecificLanguageData("table_FieldMustBeUnique", table_FieldMustBeUnique);
    	}
    	return resource;
    }
    public String addSimpleEditFormField(String column,String title,boolean required)
    {
    	editColumnHeaderMap.put(column, new EditFormField(column,title,required,dbHelp.getResource()));
    	return column;
    }
    public String addDateTimeEditFormField(String column,String title,boolean required,String pattern,
    		boolean calendarInput)
    {
    	String newColumn = "generated."+column;
    	AEDateTimeFormatter formatter=new AEDateTimeFormatter(column,pattern,!required);
    	container.addGeneratedDataStringFormatter(newColumn, formatter);
    	if (calendarInput) editColumnHeaderMap.put(column, new DateEditFormField(column,title,required,dbHelp.getResource(),pattern));
    	else 
    	editColumnHeaderMap.put(newColumn, new EditFormField(newColumn,title,required,dbHelp.getResource()));
    	return newColumn;
    }
    public String addListEditFormField(String column,String title,boolean required,String listing,int options)
    {
    	Class<?> keyType = container.getType(column);
    	ListEditFormField field=new ListEditFormField(column,title,required,
    			keyType,listing,dbHelp.getResource(),options);
    	editColumnHeaderMap.put(column,field);
    	LinkedHashMap<Object,String> map = field.getListMap();
    	String newKey = "generated."+column;
        container.addStringListGeneratedDataForColumn(column, newKey, map,dbHelp.getResource());
        return column;
    }
    public String addGeneratedDataListField(String column,String listing,int options)
    {
       	Class<?> keyType = container.getType(column);
    	ListEditFormField field=new ListEditFormField(column,"title",false,
    			keyType,listing,dbHelp.getResource(),options);
    	//editColumnHeaderMap.put(column,field);
    	LinkedHashMap<Object,String> map = field.getListMap();
    	String newKey = "generated."+column;
        container.addStringListGeneratedDataForColumn(column, newKey, map, dbHelp.getResource());
        return newKey;    	
    }
    public String addGeneratedDataListFieldToSpecificContainer(String column,String listing,int options,
    		String containerName,String newColumnName) throws Exception
    {
    	AETableContainer specContainer = dbHelp.getAETableContainer(containerName);
       	Class<?> keyType = specContainer.getType(column);
    	ListEditFormField field=new ListEditFormField(column,"Ok",false,
    			keyType,listing,dbHelp.getResource(),options);
    	
    	LinkedHashMap<Object,String> map = field.getListMap();
    	
        specContainer.addStringListGeneratedDataForColumn(column, newColumnName, map,dbHelp.getResource());
        
        return newColumnName;    	
    }
    public String addListEditFormField(String column,String title,boolean required,String listing)
    {
    	return addListEditFormField(column,title,required,listing,0);
    }
    public String addTableListEditFormField(String column,String title,boolean required,String listing) throws Exception
    {
    	Class<?> keyType = container.getType(column);
    	editColumnHeaderMap.put(column, new TableListEditFormField(column,title,required,
    			keyType,listing,dbHelp.getResource()));
    	return column;
    }
    public void addEditFormSimpleDependence(String mainEditForm,String subordinatedEditForm,String field,String operation,Object value)
    {
    	Filter filter = new Compare.Equal(field, value);
    	EditFormField mainField = editColumnHeaderMap.get(mainEditForm);
    	if (mainField==null) throw new RuntimeException("Invalid edit form column name: "+mainEditForm);
    	EditFormField subField = editColumnHeaderMap.get(subordinatedEditForm);
    	if (subField==null) throw new RuntimeException("Invalid edit form column name: "+subordinatedEditForm);
    	int dependNr = subField.addMainVisibilityObject(mainField);
    	mainField.addSubVisibilityObject(subField, filter, dependNr);
    }
    @Override
    public boolean isLikeFilterForEachColumnToBeProvided()
    {
    	return likeFilter!=null;
    }
 
    public void notifyOfCompanyChange()
    {
    	//System.out.println("DefaultWindow for "+sourceData.getViewTable().toString()+" notified of company change");
    	ensureDisableFormPanel();
    	ReadAllowedStatus=false;
    	validateRights();
    }
    public interface newCompanyEvent extends java.io.Serializable
    {
    	public void notifyOfNewCompany(Integer id);
    }
    public void placeCompanyComboBoxAtRightSideOfMenu() throws Exception
    {
    	menuLevel_RightAdjusted_AdditionalComponent=getCompanyComboBox(dbHelp,this,new newCompanyEvent(){

    		private static final long serialVersionUID =1L;
			@Override
			public void notifyOfNewCompany(Integer id) {
				notifyOfCompanyChange();
			}
    		
    	});
    }
    public static ComboBox getCompanyComboBox(DatabaseHelper dbHelp,Component baseComponent,
    		newCompanyEvent event) throws Exception
    {
    	final ComboBox CompCombo = new ComboBox();
    	final DatabaseHelper dbHelper =dbHelp;
    	final Component rootComponent = baseComponent;
    	final newCompanyEvent companyEvent = event;
		CompCombo.setImmediate(true);
		CompCombo.setNullSelectionAllowed(false);
		CompCombo.setContainerDataSource(dbHelp.getCompContainer());
		CompCombo.setItemCaptionPropertyId("name");
		Object id = dbHelper.getCompanyId();
		if (id==null || !dbHelp.getCompContainer().containsId(id))
		{
			id = dbHelper.getCompContainer().firstItemId();
			dbHelper.setCompanyId(id);
		}
		CompCombo.select(id);
		CompCombo.addListener(new Property.ValueChangeListener() {
			
			private static final long serialVersionUID = 3553727834189583715L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				
				Object id = CompCombo.getValue();
				//System.out.println("ComboBox fired valueChange for "+id);
				if (!(id instanceof Integer)){
					id = Integer.parseInt(id.toString());
				}
				if (!id.equals(dbHelper.getCompanyId())){
					try	{
					   dbHelper.setCompanyId(id);
					} catch(Exception e) {
			        	AEHelper.logException(e,"Company selection");
			        	rootComponent.getWindow().showNotification(dbHelper.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
					} 
				}
           	    if (companyEvent!=null) companyEvent.notifyOfNewCompany((Integer)id); 
			}
			
		});
		dbHelp.addCompanyListener(new Property.ValueChangeListener() {
			/**
			 * 
			 */
			private static final long serialVersionUID = -4482321290539424815L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				
				Object id = CompCombo.getValue();	
                if (id!=null && !(id instanceof Integer))
                {
               	 id = Integer.parseInt(id.toString());
                }
                if (id==null || !id.equals(dbHelper.getCompanyId()))
                {
               	    CompCombo.setValue(dbHelper.getCompanyId());
                }
			}
			
		});
		return CompCombo;
    }
    @Override
   public int getEditFormFieldAmount()
   {
          if (editColumnHeaderMap==null) return 0;
          return editColumnHeaderMap.size();
   }
    @Override
    public boolean isFormReadyForNewEditDelete()
    {
        return true;
    }
    @Override
    public boolean isEditFormDetached()
    {
         return false;
    }
    @Override
    public String getDesignEditFormDetachedWidth()
    {
          return "400px";
    }
    @Override
    public String getDesignEditFormDetachedHeight()
    {
          return "500px";
    }
    @Override
    public String getDesignScrollableTableHeight()
    {
          return likeFilter==null?"280px":"430px";
    }
    @Override
    public String getDesignTableHeight()
    {
    	return likeFilter==null?"250px":"380px";
    }
    @Override
    public void updateLocaleInfoOfEditFormFields(ResourcePool vresource,boolean activeEdit)
    {
    	
    }
	@Override
	public String getFirstSortColumn() {
		return null;
	}
	@Override
	public boolean getFirstSortOrder() {
		return true;
	}
	@Override
	 public boolean isRefreshButtonPresent()
	 {
		 return true;
	 }
}
